package com.wangdao.wechatmall.typehandler;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.aspectj.weaver.ast.Var;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(Boolean.class)//映射的Java类型
@MappedJdbcTypes(JdbcType.TINYINT)//映射的jdbc类型
public class TinyintTypeHandler implements TypeHandler<Boolean> {

    ObjectMapper objectMapper = new ObjectMapper();

    //输入映射  Boolean → Tinyint
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(aBoolean);
        preparedStatement.setString(i, value);

    }

    //输出映射
    //Tinyint → Boolean
    @Override
    public Boolean getResult(ResultSet resultSet, String s) throws SQLException {
        int anInt = resultSet.getInt(s);
        return transfer(anInt);
    }


    @Override
    public Boolean getResult(ResultSet resultSet, int i) throws SQLException {
        int anInt = resultSet.getInt(i);
        return transfer(anInt);
    }

    @Override
    public Boolean getResult(CallableStatement callableStatement, int i) throws SQLException {
        int anInt = callableStatement.getInt(i);
        return transfer(anInt);
    }

    private Boolean transfer(int anInt) {
        return anInt == 1;
    }

}
